//
//  NearstationVC.swift
//  placepic
//
//  Created by elesahich on 2020/07/05.
//  Copyright © 2020 elesahich. All rights reserved.
//
import UIKit
import Alamofire

class NearstationVC: UIViewController {
    
    @IBOutlet weak var stackviewHeight: NSLayoutConstraint!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    let nullpageView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.white
        v.frame = CGRect.zero
        v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return v
    }()
    
    /// `@서버에서 역이 Static으로 주입되는 모델`
    var stationModel: [SubwayData] = []
    
    /// 1 .CollectionView Model이 주입이 되어야 함
    /// 2. Reload 되어야 함 - 되면서 Hidden이 풀려야 함 그럴거면 진짜 TVC 로직을 따는게 좋아보임
    
    /// `TableView에 나오는 Model`
    var searchTemporaryModel: [SubwayData] = []
    /// `CollectionView에 나오는 모델` >> `UploadVC에 주입될 모델`
    var collectionViewModel: [SubwayData] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setCollectionView()
        setNavigationBar()
        setTextfield()
        setSearchbarHeight()
        setTableView()
        setDefaultRequest()
        makeupNilPageView()
    }
}

extension NearstationVC {
    
    private func makeupNilPageView() {
        tableView.addSubview(nullpageView)
       
        let nulllabel: UILabel = {
            let label = UILabel()
            label.font = .boldSystemFont(ofSize: 14)
            label.textColor = UIColor.blueGray30
            label.text = "해당 장소와 가까운 역을 추가해보세요."
            label.frame = CGRect.init(x: 30, y: 200, width: 100, height: 50)
            return label
        }()
        
        let subwayImageView: UIImageView = {
            let imgView = UIImageView()
            imgView.image = UIImage(named: "subwayIc")
            imgView.frame = CGRect.zero
            imgView.contentMode = .scaleAspectFill
            return imgView
        }()
        
        nulllabel.translatesAutoresizingMaskIntoConstraints = false
        subwayImageView.translatesAutoresizingMaskIntoConstraints = false
        
        nullpageView.addSubview(nulllabel)
        nullpageView.addSubview(subwayImageView)
        
        let constraints = [
            subwayImageView.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
            subwayImageView.topAnchor.constraint(equalTo: nullpageView.topAnchor, constant: 74),
            subwayImageView.heightAnchor.constraint(equalToConstant: 44),

            nulllabel.topAnchor.constraint(equalTo: subwayImageView.bottomAnchor, constant: 12),
            nulllabel.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
            nulllabel.heightAnchor.constraint(equalToConstant: 21),

        ]
        NSLayoutConstraint.activate(constraints)
    }
}

// MARK: - setup Functions
extension NearstationVC {
    
    private func setTextfield() {
        searchTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        searchTextField.backgroundColor = UIColor.blueGray20
        searchTextField.layer.cornerRadius = 6
        searchTextField.layer.borderWidth = 1
        searchTextField.layer.borderColor = UIColor.white.cgColor
        searchTextField.clipsToBounds = true
        searchTextField.setLeftPaddingPoints(30)
        searchTextField.placeholder = "가까운 지하철 역을 검색해보세요"
        searchTextField.delegate = self
    }
    
    @objc
    private func textFieldDidChange(_ textField: UITextField) {
        if searchTextField.hasText {
            let transform = CGAffineTransform(translationX: 0, y: 500)
            UIView.animate(withDuration: 1,
                           delay: 0,
                           usingSpringWithDamping: 1,
                           initialSpringVelocity: 1,
                           options: .curveEaseIn,
                           animations: {
                            self.nullpageView.transform = transform
            }, completion: { (_) in
                UIView.animate(withDuration: 0.3,
                               animations: {
                                self.nullpageView.alpha = 0
                })
            })
            searchTemporaryModel.removeAll()
            self.tableView.reloadData()
        } else {
            UIView.animate(withDuration: 0.7,
                           delay: 0,
                           usingSpringWithDamping: 1,
                           initialSpringVelocity: 1,
                           options: .curveEaseOut,
                           animations: {
                            self.nullpageView.transform = .identity
                            self.nullpageView.alpha = 1
            }, completion: nil)
        }
        
        func filterContentForSearchText(searchText: String) {
            let filtered = self.stationModel.filter() { $0.subwayName == searchText }
            self.searchTemporaryModel.append(contentsOf: filtered)
            
            for i in 0..<stationModel.count {
                if (stationModel[i].subwayName?.contains(searchText))! {
                    searchTemporaryModel.append(stationModel[i])
                }
            }
            let set = Set(searchTemporaryModel)
            let setArray = set.sorted() {
                guard let subwayA = $0.subwayName else { return false }
                guard let subwayB = $1.subwayName else { return false }
                return subwayA > subwayB
            }

            searchTemporaryModel = Array(setArray)
            tableView.reloadData()
        }
        searchTemporaryModel = []
        let searchText = searchTextField.text ?? ""
        filterContentForSearchText(searchText: searchText)
    }
    
    /// Model에 데이터가 없으면 0 있으면 1
    /// tableViewCell이 눌리는 경우마다 발생해야 함 ( default : Hide)
    private func setSearchbarHeight() {
        if collectionViewModel.count == 0 {
            collectionView.isHidden = true
            stackviewHeight.constant = 53
            UIView.animate(withDuration: 0.3,
                           animations: {
                            self.view.layoutIfNeeded()
            })
        } else {
            self.collectionView.isHidden = false
            self.stackviewHeight.constant = 106
            UIView.animate(withDuration: 0.3,
                           animations: {
                            self.view.layoutIfNeeded()
            })
        }
    }
    
    private func setTableView() {
        tableView.register(UINib.init(nibName: "ShowStationTVC", bundle: nil), forCellReuseIdentifier: "ShowStationTVCIdentifier")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
    }
    
    private func setCollectionView() {
        collectionView.register(UINib.init(nibName: "NearstationCVC", bundle: nil), forCellWithReuseIdentifier: "NearstationCVCIdentifier")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
    }
    
    private func setNavigationBar() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }
        
        navigationBar.isTranslucent = true
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
        let leftButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "backArrowIc"),
                                                          style: .plain,
                                                          target: self,
                                                          action: #selector(dismissVC))
        navigationItem.leftBarButtonItem = leftButton
        
        let button: UIButton = {
            let btn = UIButton()
            btn.setTitle("확인", for: .normal)
            btn.titleLabel?.font = .systemFont(ofSize: 15)
            btn.setTitleColor(.warmPink, for: .normal)
            return btn
        }()
        
        button.addTarget(self,
                         action: #selector(doneButtonTapped),
                         for: .touchUpInside)
        
        let rightButton: UIBarButtonItem = UIBarButtonItem(customView: button)
        navigationItem.rightBarButtonItem = rightButton
    }
    
    @objc
    private func dismissVC() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc
    private func doneButtonTapped() {
        if collectionViewModel.count >= 4 {
            alertaction()
        } else {
            NotificationCenter.default.post(name: .searchSubwayNotification, object: nil, userInfo: ["model": collectionViewModel])
            dismiss(animated: true, completion: nil)
        }
    }
    
    func alertaction() {
        let alert = UIAlertController(title: "경고",
                                      message: "역은 3개까지 선택할 수 있어요!", preferredStyle: UIAlertController.Style.alert)
        let cancel = UIAlertAction(title: "확인",
                                   style: .cancel,
                                   handler : nil )
        alert.addAction(cancel)
        present(alert, animated: true, completion: nil)
    }
}

//MARK: - 통신
extension NearstationVC {
    
    func setDefaultRequest() {
        SubwayServeices.subwayServices.getKeywordRequest { data in
            if let metaData = data {
                self.stationModel.append(contentsOf: metaData)
                self.tableView.reloadData()
            }
        }
    }
}


extension NearstationVC: UICollectionViewDelegateFlowLayout { }
extension NearstationVC: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.collectionView.deleteItems(at: [indexPath])
        self.collectionViewModel.remove(at: indexPath.item)
        self.collectionView.reloadData()
        setSearchbarHeight()
        UIView.animate(withDuration: 0.3,
                       animations: {
                        self.view.layoutIfNeeded()
        })
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionViewModel.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        /// `@ sizethatFits라는 메소드 있으니 사용해봅시다 @`
        let widthexceptlabel: CGFloat = 38
        let cellwidth: CGFloat = (collectionViewModel[indexPath.item].subwayName?.width(withConstrainedHeight: 30, font: .systemFont(ofSize: 13)))! + widthexceptlabel
        let height: CGFloat = 30
        
        return CGSize(width: cellwidth + 15, height: height)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NearstationCVCIdentifier", for: indexPath) as? NearstationCVC else {
            return UICollectionViewCell()
        }
        setSearchbarHeight()
        cell.model = collectionViewModel[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 14, left: 15, bottom: 0, right: 15)
    }
}

extension NearstationVC: UITableViewDelegate { }
extension NearstationVC: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        collectionViewModel.append(searchTemporaryModel[indexPath.row])
        let set = Set(collectionViewModel)
        collectionViewModel = Array(set)
        collectionView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    
    }  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if searchTemporaryModel.count == 0 {
            return 0
        } else {
            return searchTemporaryModel.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ShowStationTVCIdentifier", for: indexPath) as? ShowStationTVC
            else {
            return UITableViewCell()
        }
        
        if searchTemporaryModel.count == 0 {
            cell.model = stationModel[indexPath.row]
            return cell
        } else {
            cell.model = searchTemporaryModel[indexPath.row]
            return cell
        }
    }
}

extension NearstationVC: UITextFieldDelegate {
  
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        searchTextField.resignFirstResponder()
        return true
    }
}
